<?php
namespace app\index\validate;
use think\Validate;
use think\Db;
class ApiV extends Validate{
    protected $rule = [
    	'nickName'		=> ['require'],
    	'gender'		=> ['require'],
    	'city'			=> ['require'],
    	'province'		=> ['require'],
    	'avatarUrl'		=> ['require'],
    	'temp_code'		=> ['require'],
    	'name'			=> ['require'],
    	'idcard'		=> ['require','unique:users','checkIdcard'],
    	'idcard_img'	=> ['require'],
    	'sms_type'		=> ['require'],
    	'phone'			=> ['require','checkphone'],
    	'smscode'		=> ['require','checkSmscode:sms'],
    ];
	protected $message=[
		'nickName.require'	=>'昵称不能为空',
		'gender.require'	=>'性别不能为空',
		'city.require'		=>'城市名不能为空',
		'province.require'	=>'省份名不能为空',
		'avatarUrl.require'	=>'头像地址不能为空',
		'temp_code.require'	=>'临时授权码不能为空',
		'name.require'		=>'真实姓名不能为空',
		'idcard.require'	=>'身份证号不能为空',
		'idcard.unique'		=>'身份证号已存在',
		'idcard.checkIdcard'=>'该身份证无效',
		'idcard_img.require'=> '身份证图片不能为空',
		'sms_type.require'	=> '短信验证类型不能为空',
		'phone.require'	    => '手机号码不能为空',
		'phone.checkphone'  => '手机号码格式错误',
		'smscode.require'		=> '手机验证码不能为空',
		'smscode.checkSmscode'	=> '验证码错误或已过期',
	];
	protected $scene=[
		'login1'=>[		//小程序授权登录必备参数
			'nickName',
			'gender',
			'city',
			'province',
			'avatarUrl',
			'temp_code'
		],
		'check_idcard'=>[
			'name',
			'idcard'=>'require|unique:users|checkIdcard',
			'idcard_img_a'
		]
	];
	protected function checkIdcard($val){
//		return true;
		return isIdCard($val);
	}
	//验证验证码
	protected function checkSmscode($key,$rule,$data){
		$smsLog = Db::name('smsLog')->where(['phone' => $data['phone'], 'stat' => 1])->order('id desc')->find();
		if(!$smsLog){
			return false;
		}elseif($smsLog['smscode'] != $data['smscode']){
			return false;
		}elseif($smsLog['exp_time'] < time()){
			Db::name('smsLog')->where('id',$smsLog['id'])->update(['stat' => 2]);
			return false;
		}else{
			Db::name('smsLog')->where('id',$smsLog['id'])->update(['stat' => 2]);
			return true;
		}
	}
	//验证手机号
	protected function checkphone($val){
		return check_mobile($val);
	}
}
